import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AuthState, User } from '../../types';

// 从localStorage获取初始用户信息
const getUserFromStorage = (): User | null => {
  try {
    const storedUser = localStorage.getItem('user');
    return storedUser ? JSON.parse(storedUser) : null;
  } catch (error) {
    console.error('Failed to parse user from localStorage:', error);
    // 如果解析失败，清除可能损坏的数据
    localStorage.removeItem('user');
    return null;
  }
};

// 清除所有认证相关的本地存储
const clearAuthStorage = () => {
  try {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    sessionStorage.removeItem('token');
    sessionStorage.removeItem('user');

    // 清除可能存在的其他相关缓存
    const authRelatedKeys = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && (key.includes('auth') || key.includes('user') || key.includes('token'))) {
        authRelatedKeys.push(key);
      }
    }

    // 删除找到的相关键
    authRelatedKeys.forEach(key => localStorage.removeItem(key));
    console.log('All auth storage cleared successfully');
  } catch (error) {
    console.error('Error clearing auth storage:', error);
  }
};

const initialState: AuthState = {
  user: getUserFromStorage(),
  token: localStorage.getItem('token'),
  loading: false,
  error: null,
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setCredentials: (
      state,
      action: PayloadAction<{
        token: string;
        user: {
          id: number;
          nick_name?: string;
          nickname?: string;
          userName?: string;
          username?: string;
          role: number;
          expired_at: number;
        };
      }>
    ) => {
      // 先清除旧数据
      clearAuthStorage();

      const { user, token } = action.payload;

      // 记录原始数据用于调试
      console.log('Received login data:', {
        token: token ? 'exists' : 'missing',
        user: user ? {
          id: user.id,
          role: user.role,
          expired_at: user.expired_at,
          has_nick_name: !!user.nick_name
        } : 'missing'
      });

      if (!user || !token) {
        console.error('Invalid login data received:', { hasUser: !!user, hasToken: !!token });
        return;
      }

      // 确保所有必要字段都存在
      const userData: User = {
        id: user.id,
        nick_name: user.nick_name || user.nickname || user.userName || user.username || '用户',
        role: typeof user.role === 'number' ? user.role : 1, // 确保role是数字
        expired_at: user.expired_at || Math.floor(Date.now() / 1000) + 86400 // 如果没有过期时间，默认24小时
        ,
        is_deleted: false,
        birthDay: undefined,
        mobile: '',
        gender: 'male'
      };

      // 确保过期时间格式正确（转换为秒级时间戳）
      if (userData.expired_at > 9999999999) { // 如果是毫秒时间戳
        userData.expired_at = Math.floor(userData.expired_at / 1000);
      }

      // 记录处理后的数据用于调试
      console.log('Processed user data:', {
        id: userData.id,
        role: userData.role,
        expired_at: userData.expired_at,
        timestamp: new Date().toISOString()
      });

      // 更新 Redux store
      state.user = userData;
      state.token = token;

      // 同时更新 localStorage
      try {
        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(userData));

        // 验证数据是否正确保存
        const savedUser = localStorage.getItem('user');
        const parsedUser = savedUser ? JSON.parse(savedUser) : null;

        console.log('Verification of saved data:', {
          saved_role: parsedUser?.role,
          expected_role: userData.role,
          match: parsedUser?.role === userData.role,
          timestamp: new Date().toISOString()
        });

        if (!parsedUser || parsedUser.role !== userData.role) {
          console.error('Role mismatch after save:', {
            expected: userData.role,
            saved: parsedUser?.role
          });
        }
      } catch (error) {
        console.error('Failed to save or verify auth data:', error);
      }
    },
    updateUser: (state, action: PayloadAction<Partial<User>>) => {
      if (state.user) {
        const updatedUser = { ...state.user, ...action.payload };
        state.user = updatedUser;

        // 打印调试信息
        console.log('Updating user in Redux store:', {
          previousUser: state.user,
          updates: action.payload,
          updatedUser,
          timestamp: new Date().toISOString()
        });

        // 同步到 localStorage
        try {
          localStorage.setItem('user', JSON.stringify(updatedUser));
        } catch (error) {
          console.error('Failed to update user in localStorage:', error);
        }
      }
    },
    logout: (state) => {
      // 打印调试信息
      console.log('Logging out:', {
        previousUser: state.user,
        timestamp: new Date().toISOString()
      });

      // 清除 Redux store
      state.user = null;
      state.token = null;

      // 彻底清除所有认证相关的本地存储
      clearAuthStorage();

      console.log('Logout complete - all auth data cleared');
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
    },
  },
});

export const { setCredentials, updateUser, logout, setLoading, setError } = authSlice.actions;
export default authSlice.reducer;